#include "sshmanager.h"
#include "sshsession.h"
#include <QDebug>
#include <QRandomGenerator>
#include <QCryptographicHash>
#include <QDateTime>

SshManager::SshManager(QObject *parent) : QObject(parent)
{
    // 初始化libssh2
    if (!initializeLibssh2()) {
        qCritical() << "Failed to initialize libssh2";
    }
}

SshManager::~SshManager()
{
    // 关闭所有会话
    closeAllSessions();

    // 清理libssh2
    cleanupLibssh2();
}

SshSession *SshManager::createSession(const ConnectionConfig &config)
{
    QMutexLocker locker(&m_mutex);

    // 生成会话ID
    QString sessionId = generateSessionId();

    // 创建新的SSH会话
    SshSession *session = new SshSession(config, sessionId, this);

    // 连接信号
    connect(session, &SshSession::stateChanged, this, [this, sessionId](SshSession::SessionState state) {
        if (state == SshSession::Ready) {
            emit sessionConnected(sessionId);
        } else if (state == SshSession::Error || state == SshSession::Disconnected) {
            emit sessionDisconnected(sessionId);
        }
    });

    connect(session, &SshSession::error, this, [this, sessionId](const QString &error) {
        emit sessionError(sessionId, error);
    });

    // 添加到会话映射
    m_sessions.insert(sessionId, session);

    qDebug() << "Created SSH session:" << sessionId << "for host:" << config.host;

    return session;
}

SshSession *SshManager::getSession(const QString &sessionId)
{
    QMutexLocker locker(&m_mutex);
    return m_sessions.value(sessionId);
}

void SshManager::closeSession(const QString &sessionId)
{
    QMutexLocker locker(&m_mutex);

    SshSession *session = m_sessions.value(sessionId);
    if (session) {
        qDebug() << "Closing SSH session:" << sessionId;

        // 断开连接
        session->disconnect();

        // 从映射中移除
        m_sessions.remove(sessionId);

        // 删除会话对象
        session->deleteLater();

        emit sessionDisconnected(sessionId);
    }
}

void SshManager::closeAllSessions()
{
    QMutexLocker locker(&m_mutex);

    qDebug() << "Closing all SSH sessions";

    // 复制会话列表以避免迭代时修改
    QList<SshSession*> sessions = m_sessions.values();

    for (SshSession *session : sessions) {
        QString sessionId = session->sessionId();
        session->disconnect();
        m_sessions.remove(sessionId);
        session->deleteLater();
    }

    m_sessions.clear();
}

QList<SshSession*> SshManager::getActiveSessions()
{
    QMutexLocker locker(&m_mutex);
    return m_sessions.values();
}

bool SshManager::isSessionActive(const QString &sessionId)
{
    QMutexLocker locker(&m_mutex);

    SshSession *session = m_sessions.value(sessionId);
    return session && session->isConnected();
}

QString SshManager::generateSessionId() const
{
    // 生成唯一的会话ID
    QString timestamp = QString::number(QDateTime::currentMSecsSinceEpoch());
    QString random = QString::number(QRandomGenerator::global()->generate());
    QString data = timestamp + random + QString::number(quintptr(this));

    QString hash = QCryptographicHash::hash(data.toUtf8(), QCryptographicHash::Sha256).toHex();
    return hash.left(16); // 取前16个字符作为会话ID
}

bool SshManager::initializeLibssh2()
{
    // 初始化libssh2
    int rc = libssh2_init(0);
    if (rc != 0) {
        qCritical() << "libssh2 initialization failed, error code:" << rc;
        return false;
    }

    qDebug() << "libssh2 initialized successfully";
    return true;
}

void SshManager::cleanupLibssh2()
{
    // 清理libssh2
    libssh2_exit();
    qDebug() << "libssh2 cleaned up";
}